<?php
namespace App\Task;

use App\Job\RugbyReviewJob;
use Hyperf\DbConnection\Db;
use Hyperf\Logger\LoggerFactory;
use Hyperf\AsyncQueue\Driver\DriverFactory;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Crontab\Annotation\Crontab;

/**
 * @Crontab(
 *     rule="0 6 * * *",
 *     name="AutoGetBlog",
 *     callback="execute",
 *     memo="每天早上6点执行一次"
 * )
 */
class IrugbyReviewTask
{
    protected $logger;
    protected $queue;
    protected $loggerFactory;

    public function __construct(LoggerFactory $loggerFactory, DriverFactory $driverFactory)
    {
        $this->logger = $loggerFactory->get('tasklog', 'tasklog');
        $this->queue = $driverFactory->get('default');
        $this->loggerFactory = $loggerFactory;
    }

    public function execute()
    {
        try {
            $irugbystore_db = Db::connection('irugbystore');

            $products = $irugbystore_db->table('oc_product as p')
                ->leftJoin('oc_product_description as pd', 'p.product_id', '=', 'pd.product_id')
                ->select([
                    'p.product_id',
                    'pd.language_id',
                    'pd.name',
                    'pd.description',
                ])
                ->where('p.status', 1)
                ->limit(300)
                ->orderBy('p.date_modified','desc')
                ->get();

            if($products){
                $langs = [1 => "English", 2 => "French"];

                $productIds = $products->pluck('product_id')->toArray();

                $reviewedProductIds = $irugbystore_db->table('oc_review')
                    ->whereIn('product_id', $productIds)
                    ->pluck('product_id')
                    ->toArray();

                $unreviewedProducts = $products->filter(function ($product) use ($reviewedProductIds) {
                    return !in_array($product->product_id, $reviewedProductIds);
                });

                foreach ($unreviewedProducts as $product) {
                    $descriptionHtml = $product->description;
                    $decodedHtml = html_entity_decode($descriptionHtml, ENT_QUOTES, 'UTF-8');
                    $plainText = strip_tags($decodedHtml);

                    $this->queue->push(new RugbyReviewJob(
                        (int)$product->product_id,
                        (int)$product->language_id,
                        $product->name,
                        $plainText,
                        $langs[$product->language_id] ?? 'English',
                        'irugbystore'
                    ));
                }
            }

            $this->logger->info("IrugbyReviewTask 数据", ['product_ids' => $unreviewedProducts->pluck('product_id')->toArray()]);
        } catch (\InvalidArgumentException $e) {
            $this->logger->error("IrugbyReviewTask数据库配置错误", [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);
        } catch (\PDOException $e) {
            $this->logger->error("IrugbyReviewTask数据库连接失败", [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);
        } catch (\Throwable $e) {
            $this->logger->error("IrugbyReviewTask系统错误", [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);
        }
    }
}
